from django.shortcuts import render, HttpResponse, redirect
from app01 import models
from django.core.validators import ValidationError
from django.core.validators import RegexValidator  # 校验
from django.utils.safestring import mark_safe
from django.contrib.auth import login
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.decorators import login_required
from django import forms


# from app01.models import UserInfo
# Create your views here.
#
# def two(request):
#     #从定向
#     return redirect('https://www.baidu.com')
#
# def orm(request):#测试添加数据的类
#     # UserInfo.objects.create(name='耿子俊',password='123',age='22')
#     # UserInfo.objects.create(name='tom',password='563',age='12')
#     # UserInfo.objects.create(name='jack',password='654',age='18')
#     # UserInfo.objects.create(name='root',password='342',age='21')
#     # # UserInfo.objects.all().delete()
#     UserInfo.objects.filter(id=41).update(id=4)
#     return HttpResponse('ok')
#
# def info_list(request):
#     #获取数据库中所有用户信息
#     data_list = UserInfo.objects.all()
#     return render(request,'info_list.html',{'data_list':data_list})
#
# def info_add(request):
#     if request.method == 'GET':
#         return render(request,'info_add.html')
#     #获取用户提交的数据
#     user = request.POST.get('user')
#     pwd = request.POST.get('pwd')
#     age = request.POST.get('age')
#     #添加到数据库
#     UserInfo.objects.create(name=user,password=pwd,age=age)
#     return redirect('/info/list/')
#
# def info_delete(request):
#     nid = request.GET.get('nid')
#     UserInfo.objects.filter(id=nid).delete()
#
#     return redirect('/info/list')
@login_required
def depart_list(request):
    '''部门列表'''
    queryset = models.Department.objects.all()

    return render(request, 'depart_list.html', {'queryset': queryset})


@login_required
def depart_add(request):
    '''添加部门'''
    if request.method == 'GET':
        return render(request, 'depart_add.html')
    title = request.POST.get('title')
    models.Department.objects.create(title=title)
    return redirect('/depart/list/')


@login_required
def depart_delete(request):
    '''删除部门'''
    nid = request.GET.get('nid')
    models.Department.objects.filter(id=nid).delete()
    return redirect('/depart/list/')


@login_required
def depart_edit(request, nid):
    '''修改部门'''
    if request.method == 'GET':
        row_object = models.Department.objects.filter(id=nid).first()

        return render(request, 'depart_edit.html', {'row_object': row_object})
    title = request.POST.get('title')
    models.Department.objects.filter(id=nid).update(title=title)
    return redirect('/depart/list/')


@login_required
def user_list(request):
    '''用户列表'''
    all = models.UserInfo.objects.all()
    # for i in all:
    #     print(i.id,i.name,i.account,i.create_time.strftime("%Y-%m-%d"),i.gender,i.get_gender_display(),i.depart_id,i.depart.title)
    return render(request, 'user_list.html', {'all': all})


@login_required
def user_delete(request):
    '''删除用户'''
    nid = request.GET.get('nid')
    models.UserInfo.objects.filter(id=nid).delete()

    return redirect('/user/list/')


@login_required
def user_add(requset):
    '''新建用户'''
    if requset.method == 'GET':
        dic = {
            'gender_choices': models.UserInfo.gender_choices,
            'bm': models.Department.objects.all()
        }
        return render(requset, 'user_add.html', dic)

    user = requset.POST.get('name')
    pwd = requset.POST.get('password')
    age = requset.POST.get('age')
    account = requset.POST.get('account')
    ctime = requset.POST.get('create_time')
    depart_id = requset.POST.get('bm')
    gender = requset.POST.get('gd')
    models.UserInfo.objects.create(name=user, password=pwd, age=age, account=account, create_time=ctime,
                                   depart_id=depart_id, gender=gender)
    return redirect('/user/list/')


###########model form###########


class Model(forms.ModelForm):
    class Meta:
        model = models.UserInfo
        fields = ['name', 'age', 'password', 'account', 'create_time', 'depart', 'gender']


@login_required
def user_model_form_add(request):
    if request.method == 'GET':
        form = Model()
        return render(request, 'user_modell_form_add.html', {'form': form})
    form = Model(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/user/list')
    return render(request, 'user_modell_form_add.html', {'form': form})


@login_required
def user_edit(request, nid):
    if request.method == 'GET':
        mr = models.UserInfo.objects.filter(id=nid).first()
        form = Model(instance=mr)
        return render(request, 'user_edit.html', {'form': form})
    mr = models.UserInfo.objects.filter(id=nid).first()
    form = Model(data=request.POST, instance=mr)
    if form.is_valid():
        form.save()
        return redirect('/user/list/')
    return render(request, 'user_edit.html', {'form': form})


#############靓号管理 ############
@login_required
def num_list(request):
    data_dict = {}
    search_data = request.GET.get('q', '')
    if search_data:
        data_dict['mobile__contains'] = search_data
    # 根基用户想要访问的页面 计算出起止位置
    page = int(request.GET.get('page', 1))
    page_size = 10  # 每页显示10条数据
    start = (page - 1) * page_size
    end = page * page_size

    total_count = models.PrettyNum.objects.filter(**data_dict).order_by('-level').count()
    qus = models.PrettyNum.objects.filter(**data_dict).order_by('-level')[start:end]

    total_page_count, div = divmod(total_count, page_size)
    if div:
        total_page_count += 1

    # 计算出当前页 前五页 后五页
    plus = 5
    if total_page_count <= 2 * page + 1:
        start_page = 1
        end_page = total_page_count
    else:
        if page <= plus:  # 当前页面小于5时
            start_page = 1
            end_page = 2 * plus + 1
        else:
            # 当前页+5大于总页面时
            if (page + plus) > total_page_count:
                start_page = total_page_count - 2 * plus
                end_page = total_page_count
            else:
                start_page = page - plus
                end_page = page + plus + 1

    # 页码
    page_str_list = []

    if page > 1:
        prev = '<li class="active"><a href="?page={}">上一页</a></li>'.format(page - 1)
    else:
        prev = '<li class="active"><a href="?page={}">上一页</a></li>'.format(1)
    page_str_list.append(prev)

    for i in range(start_page, end_page + 1):
        if i == page:
            ele = '<li class="active"><a href="?page={}">{}</a></li>'.format(i, i)
        else:
            ele = '<li><a href="?page={}">{}</a></li>'.format(i, i)
        page_str_list.append(ele)

    if page < total_page_count:
        prev = '<li class="active"><a href="?page={}">下一页</a></li>'.format(page + 1)
    else:
        prev = '<li class="active"><a href="?page={}">下一页</a></li>'.format(total_page_count)
    page_str_list.append(prev)

    page_string = mark_safe("".join(page_str_list))

    return render(request, 'num_list.html', {'q': qus, 'search_data': search_data, 'page_string': page_string})


class NumModelForm(forms.ModelForm):
    # # 校验方式一
    mobile = forms.CharField(
        label='手机号',
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误111')]  # 使用正则表达式来约束手机号格式
    )

    class Meta:
        model = models.PrettyNum
        # fields = '__all__'  # 显示所有字段
        fields = ['mobile', 'price', 'level', 'status']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {'class': 'form-control', 'placeholder': field.label}

    def clean_mobile(self):  # 校验手机号是否存在
        txt_mobile = self.cleaned_data['mobile']
        exists = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()  # 返回  True或者False
        if exists:
            raise ValidationError('手机号已存在')
        return txt_mobile

    # 校验方式二
    # def clean_mobile(self):
    #     txt_mobile = self.cleaned_data['mobile']
    #     if len(txt_mobile) != 11:
    #         raise ValidationError('你输入的格式不对')
    #     return txt_mobile


@login_required
def num_add(request):
    if request.method == 'GET':
        form = NumModelForm()
        return render(request, 'num_add.html', {'form': form})
    form = NumModelForm(request.POST)
    if form.is_valid():  # 进行校验
        form.save()  # 保存数据
        return redirect('/num/list')
    return render(request, 'num_add.html', {'form': form})


@login_required
def num_delete(request):
    nid = request.GET.get('nid')
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect('/num/list/')


class NumModelForm2(forms.ModelForm):
    # mobile = forms.CharField(disabled=True,label='手机号') # 编辑不可更改
    mobile = forms.CharField(
        label='手机号',
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误'), ],  # 使用正则表达式来约束手机号格式
    )

    class Meta:
        model = models.PrettyNum
        # fields = '__all__'  # 显示所有字段
        fields = ['mobile', 'price', 'level', 'status']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {'class': 'form-control', 'placeholder': field.label}

    def clean_mobile(self):  # 校验手机号是否存在
        txt_mobile = self.cleaned_data['mobile']
        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(
            mobile=txt_mobile).exists()  # 返回  True或者False
        if exists:
            raise ValidationError('手机号已存在')
        return txt_mobile


@login_required
def num_edit(request, nid):
    if request.method == 'GET':
        mr = models.PrettyNum.objects.filter(id=nid).first()
        form = NumModelForm2(instance=mr)
        return render(request, 'num_edit.html', {'form': form})
    mr = models.PrettyNum.objects.filter(id=nid).first()
    form = NumModelForm2(data=request.POST, instance=mr)
    if form.is_valid():
        form.save()
        return redirect('/num/list/')
    return render(request, 'num_edit.html', {'form': form})


def register(request):
    """注册页面"""
    if request.method != 'POST':
        form = UserCreationForm()
    else:
        form = UserCreationForm(data=request.POST)
        if form.is_valid():
            new_1 = form.save()
            login(request, new_1)
            return redirect('/user/list/')
    context = {'form': form}
    return render(request, 'registration/register.html', context)
